﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HiStaff.Util;
using HiStaff.Base;
using HiStaff.Control;
using HiStaff.Dal;
using HiStaff.Domain.CO;
using System.Globalization;
namespace HiStaff.iTime
{
    public partial class SwipeDateRangeImport : FormBase
    {
       private const string MSG_INVALID_PERIOD = "Dữ liệu trong tệp không phù hợp với kỳ công tương ứng, không thể thực hiện việc đăng ký dữ liệu.\nVui lòng kiểm tra lại.";
        private const string DTCOL_UPDATE = "UPDATE";
        private const string DTCOL_TRUEVALUE = "TRUEVALUE";
        private const string FT_SELECTEDDATE = "#{0}#>=" + DTCOL_TRUEVALUE + " AND " + DTCOL_TRUEVALUE + ">=#{1}#";
        private OpenFileDialog openDialog;
        private DateTime impMinDate;
        private DateTime impMaxDate;

        public ERP_SY_ORGPERIOD SelectedPeriod;
        public string OrgName { get; set; }
        public decimal? OrgId { get; set; }
        public DataView DataPrepare { get; set; }

        public bool IsOverrideData
        {
            get
            {
                return chkOverideData.Checked;
            }
        }

        public SwipeDateRangeImport()
        {
            InitializeComponent();
        }

        private void SwipeDateRangeImport_Load(object sender, EventArgs e)
        {
            try
            {
                //this.DialogResult = DialogResult.No;

                base.CreateCommandBar(CommandBarManager.ActionCommand.Save,
                                      CommandBarManager.ActionCommand.Separator,
                                      CommandBarManager.ActionCommand.Exit);

                //jbtnSearchFile.PerformClick();
                //if (String.IsNullOrEmpty(lblFileUrl.Text))
                //{
                //    this.DialogResult = DialogResult.No;
                //    this.Close();
                //    return;
                //}

                //Set Org value
                //if (OrgId.HasValue)
                //{
                //    lblOrgName.Text = OrgName;
                //    jbtnSearchOrg.Tag = OrgId;
                //}

                //Set org period
                //cbxPeriod.MaxDropDownItems = 12;
                //cbxPeriod.DisplayMember = "PERIODNAME";
                //cbxPeriod.ValueMember = "PERIOD_ID";
                //cbxPeriod.DataSource = LstOrgPeriod;
                //Mac dinh lay thang thang gan nhat ky cong dang dc mo
                //if (LstOrgPeriod != null && LstOrgPeriod.Count > 0)
                //{
                //    for (int i = 0; i < LstOrgPeriod.Count - 1; i++)
                //    {
                //        if (LstOrgPeriod[i].ENDDATE.Month >= DateTime.Now.Month && LstOrgPeriod[i].STATUSCOLEX == (int)ColexStatus.Working)
                //        {
                //            //cbxPeriod.SelectedIndex = i;
                //            SelectedPeriod = LstOrgPeriod[i];
                //            lblPeriod.Text = SelectedPeriod.PERIODNAME;
                //            break;
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
                Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
        }

        private void jbtnSearchFile_Click(object sender, EventArgs e)
        {
            DataColumn colUpd;

            openDialog = new OpenFileDialog();
            openDialog.Filter = "File dữ liệu quẹt thẻ / vân tay (*.txt)|*.txt";
            openDialog.Multiselect = false;

            base.GetCommandByKey(CommandBarManager.ActionCommand.Save).Enabled = Janus.Windows.UI.InheritableBoolean.False;

            if (openDialog.ShowDialog() == DialogResult.OK)
            {

                this.Cursor = Cursors.WaitCursor;

                if (IOCommonFunction.FileInUse(openDialog.FileName))
                {
                    MessageBox.Show(string.Format(Constant.MSG_CANNOT_OPENFILE, openDialog.FileName),
                                    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                Aspose.Cells.License lc = new Aspose.Cells.License();
                string strLicense = AppDomain.CurrentDomain.BaseDirectory + "\\lib\\Aspose.Cells.lic";
                lc.SetLicense(strLicense);

                //Instantiate LoadOptions specified by the LoadFormat.
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                workbook.Open(openDialog.FileName, Aspose.Cells.FileFormatType.TabDelimited);

                Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
                DataTable dtDataPrepare = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxRow + 1, worksheet.Cells.MaxColumn + 1);

                if (dtDataPrepare.Rows.Count <= 0)
                {
                    MessageBox.Show(Constant.MSG_NOTHAVE_IMPDATA, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                colUpd = new DataColumn(DTCOL_UPDATE, typeof(int));
                colUpd.DefaultValue = 0;
                dtDataPrepare.Columns.Add(colUpd);

                colUpd = new DataColumn(DTCOL_TRUEVALUE, typeof(DateTime));
                colUpd.Expression = "Convert(SubString(Convert(Column4,'System.String'),1,10) +' '+ SubString(Convert(Column5,'System.String'),12,8),'System.DateTime')";
                dtDataPrepare.Columns.Add(colUpd);

                DataPrepare = dtDataPrepare.DefaultView;
                DataPrepare.Sort = "Column4";
                impMinDate = Convert.ToDateTime(DataPrepare[0]["Column4"]);
                impMaxDate = Convert.ToDateTime(DataPrepare[DataPrepare.Count - 1]["Column4"]);

                cldFromDate.Value = impMinDate;
                cldToDate.Value = impMaxDate;

                //if (!(SelectedPeriod.ENDDATE.Date.AddDays(1) >= impMaxDate.Date
                //    && SelectedPeriod.STARTDATE.Value.Date <= impMinDate.Date
                //    && SelectedPeriod.STATUSCOLEX == (int)ColexStatus.Working))
                //{
                //    MessageBox.Show(MSG_INVALID_PERIOD, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}

                //lblFileUrl.Text = openDialog.SafeFileName;
                //jbtnSearchFile.ToolTipText = openDialog.FileName;

                base.GetCommandByKey(CommandBarManager.ActionCommand.Save).Enabled = Janus.Windows.UI.InheritableBoolean.True;

                this.Cursor = Cursors.Default;
            }
        }

        protected override bool SaveButtonClick()
        {
            DataTable dtSelected = new DataTable();
            bool isChanged = false;
            DataRow[] drSelected;

            if (impMinDate != cldFromDate.Value)
            {
                isChanged = true;
                //impMinDate = cldFromDate.Value;
            }

            if (impMaxDate != cldToDate.Value)
            {
                isChanged = true;
                //impMaxDate = cldToDate.Value;
            }
            if (isChanged)
            {
                DataPrepare.RowFilter = (string.Format(CultureInfo.InvariantCulture.DateTimeFormat,
                                         FT_SELECTEDDATE, impMaxDate.Date.AddDays(0.999999), impMinDate));
                dtSelected = DataPrepare.ToTable(true, "Column2", "Column3", DTCOL_TRUEVALUE, DTCOL_UPDATE);
            }

            this.DialogResult = DialogResult.OK;

            this.Close();
            return true;
        }
    }
}
